package YahooFinance.network;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import YahooFinance.network.AsyncHttpClient.HttpMethod;

public class NetworkService {

	static NetworkService sharedInstance;

	public static NetworkService sharedInstance() {
		if (sharedInstance == null) {
			sharedInstance = new NetworkService();
		}
		return sharedInstance;
	}

	public static final String APP_VERSION = "1.0";

	public NetworkService() {
		//
	}

	String boolValue(boolean isTrue) {
		return isTrue ? "1" : "";
	}

	String emptyForNull(String s) {
		return (s == null) ? "" : s;
	}

	String encodeParameters(HashMap<String, String> parameters) {
		boolean isFirst = true;
		StringBuilder sb = new StringBuilder();
		for (Map.Entry<String, String> entry : parameters.entrySet()) {
			sb.append(isFirst ? "?" : "&");
			isFirst = false;
			sb.append(entry.getKey());
			sb.append("=");
			if (entry.getValue() == null) {
				entry.setValue("");
			}
			try {
				sb.append(URLEncoder.encode(entry.getValue(), "ISO-8859-2"));
			} catch (UnsupportedEncodingException e) {
				sb.append(entry.getValue());
			}
		}
		return sb.toString();
	}

	/**
	 * getResourceFromUrl
	 * 
	 * @param delegate
	 * @param _url
	 */
	public void getResourceFromUrl(final FetchStringDelegate delegate,
			String _url, String dataType) {

//		HashMap<String, String> optParams = new HashMap<String, String>();
//		optParams.put("optParam", null);
//		optParams.put("datatype", dataType);

		AsyncHttpClient.startRequestWithDelegate(HttpMethod.GET, null,
				_url, new AsyncHttpDelegate() {

					public void responseReceived(Object data,
							String responseText, String fileName) {

						delegate.fetchSuccessWithString(responseText);

					}

					public void requestFailed(Exception e, String exptParam) {
						delegate.fetchFailed();
					}

				});

		return;
	}
}
